import {ChangeDetectorRef, Component, ViewChild} from '@angular/core';
import {Content,IonicPage, NavController, NavParams, Select, ToastController} from 'ionic-angular';
import {ClientCompensationProvider} from "../../../providers/client/client-compensation/client-compensation.provider";
import {CallNumber} from "@ionic-native/call-number";
import * as moment from "moment";
import {ClientNoteEditProvider} from "../../../providers/client/client-note/client-note-edit/client-note-edit.provider";
import {InfiniteScrollModel} from "../../../model/common/infinite-scroll.model";
import {MessageBushService} from "../../../services/common/message-bush.service";
import {TabsPage} from "../../tabs/tabs";
import {SideMenuService} from "../../../services/common/side-menu.service";
import {ClientFilterComponent} from "../../../components/pages/client/client-filter/client-filter.component";
import {ClientFilterWayModel} from "../../../model/pages/client/client-list/client.model";
import {LoadingService} from "../../../services/common/loading.service";
import {CallNumberService} from "../../../services/native/call-number/call-number.service";
import {AdpActionSheetController} from "../../../components/common/adp-action-sheet/adp-action-sheet-controller";

/**
 * 理赔客户
 */
@IonicPage()
@Component({
    selector: 'page-client-compensation',
    templateUrl: 'client-compensation.html',
    providers: [
        ClientCompensationProvider,
        CallNumber,
        ClientNoteEditProvider,
        SideMenuService,
        LoadingService,
        CallNumberService
    ]
})
export class ClientCompensationPage extends InfiniteScrollModel {
    private clientCompenModels: Array<any>;
    public searchKeyword: string;
    infiniteScroll = null;
    public totalNum;
    currentMobileList;
    currentMobile;
    clientTotalDes: string;
    isViewDidLoad = false;
    isArriveBottom = false;
    isLoad: boolean = false;

    get clientItemHeight(): string {
        const windowW = window['innerWidth'];
        return (windowW * 38.34 / 100) + 'px';
    }

    @ViewChild(Content) content: Content;
    @ViewChild('selectMobile') selectMobile: Select;
    isScrolling = false;

    @ViewChild('clientFilterTool') clientFilterTool: ClientFilterComponent;
    clientSortPage = ClientFilterWayModel.ClientCompensationListPage;
    dataItemSearchWrapper = {
        isSearchWrapper:true
    };

    constructor(public navCtrl: NavController,
                public navParams: NavParams,
                public clientComProvider: ClientCompensationProvider,
                private callNumber: CallNumber,
                private clientNoteEditProvider: ClientNoteEditProvider,
                public toastCtrl: ToastController,
                private sideMenuService: SideMenuService,
                public changeRef: ChangeDetectorRef,
                public tabsPage: TabsPage,
                private load: LoadingService,
                public adpActionSheetController:AdpActionSheetController,
                private callNumberService: CallNumberService) {
        super();
    }

    ionViewDidLoad() {
        this.isViewDidLoad = true;
        this.getClientList(0);
        this.isViewDidLoad = false;
    }

    ionViewDidEnter() {
        const flag = MessageBushService.getMessage(MessageBushService.keys.compensationClientListUpdated);
        if (flag == "1" && !this.isViewDidLoad) {
            this.ionViewDidLoad();
            MessageBushService.setMessage(MessageBushService.keys.compensationClientListUpdated, '0');
        }
    }

    openRoot = (name, index) => this.openTab(name, index);

    openMenu(myEvent) {
        this.sideMenuService.openSideMenu(myEvent)
    }

    openTab(name, index) {
        this.navCtrl.popToRoot();
        this.tabsPage.openPage({name: name, index: index});
    }

    scrollStart(e) {
        this.isScrolling = true;
    }

    scrollEnd(e) {
        this.isScrolling = false;
    }

    /**
     * 获取首页数据
     * @returns {Promise<void>}
     */
    getClientList(notloading = 0, callback = null) {
        this.pageParams.pageNum = 1;
        this.pageParams.pageSize = 1;
        if (notloading !== 1) {
            this.load.showLoading();
        }

        this.clientComProvider.getClientList(notloading, this.pageParams).subscribe(res => {
            this.pageParams.pageSize = res.total;
            if (!res || res.total < 1) {
                this.clientCompenModels = [this.dataItemSearchWrapper];
                this.clientTotalDes = '(0)';
                if (callback) callback();
                this.load.dismissLoading();
                this.isLoad = true;
                return;
            } else {
                this.clientTotalDes = `(${res.total})`;
            }

            return this.clientComProvider.getClientList(1, this.pageParams).subscribe((res) => {
                this.pageInfo = res;
                this.isLoad = true;
                if (this.pageInfo.list && this.pageInfo.list.length) {
                    this.clientCompenModels = this.pageInfo.list;
                    //过滤为空的电话号码
                    this.clientCompenModels = this.clientComProvider.checkMobileNull(this.clientCompenModels);
                } else {
                    this.clientCompenModels = [];
                }
                if(this.clientCompenModels.indexOf(this.dataItemSearchWrapper)==-1){
                    this.clientCompenModels.unshift(this.dataItemSearchWrapper);
                }
                if (callback) {
                    callback();
                }
                this.load.dismissLoading();
            }, error => {
                if(this.clientCompenModels.indexOf(this.dataItemSearchWrapper)==-1){
                    this.clientCompenModels.unshift(this.dataItemSearchWrapper);
                }
                if (callback) {
                    callback();
                }
                this.load.dismissLoading();
            });

        }, error2 => {
            if (callback) {
                callback();
            }
            this.load.dismissLoading();
        });
    }

    scrolling(){
        const dimensions = this.content.getContentDimensions();
        if(!this.clientCompenModels || this.clientCompenModels.length<5){
            return;
        }
        const temp1 = dimensions.scrollHeight-dimensions.scrollTop-dimensions.contentHeight<100;
        if(temp1 !== this.isArriveBottom){
            this.isArriveBottom = temp1;
            this.changeRef.detectChanges();
        }

    }

    searchedHandle(searchKeyword){
        this.searchKeyword = searchKeyword;
        this.pageParams.pageNum = 1;
        if (this.infiniteScroll) this.infiniteScroll.enable(true);
        if (this.searchKeyword) {
            this.pageParams.condition.keyword = this.searchKeyword.trim();
        } else {
            this.pageParams.condition.keyword = '';
        }
        this.getClientList();
    }

    /**
     * 回到顶部
     */
    goUp() {
        if (this.isScrolling) {
            setTimeout(() => {
                this.goUp();
            }, 300);
            return;
        }
        this.content.scrollToTop();
    }

    /**
     * 日期格式化
     */
    timeFormat(date) {
        if (date == null) {
            return ""
        } else {
            return moment(date).format("YYYY/MM/DD");

        }
    }

    /**
     *  toast 提示信息
     * @param {string} message 提示内容
     * @param {string} position 显示位置
     */
    toast(message: string, position: string) {
        this.toastCtrl.create({
            message: message,
            position: 'middle',
            duration: 1200
        }).present();
    }

    /**
     * 格式化分数
     * @param num
     * @returns {string}
     */
    toThousands(num) {
        var num = (num || 0).toString(), result = '';
        while (num.length > 3) {
            result = ',' + num.slice(-3) + result;
            num = num.slice(0, num.length - 3);
        }
        if (num) {
            result = num + result;
        }
        return result;
    }

    /**
     * 打电话按钮
     */
    currentCust;

    nativeCallPhone(num?) {
        if (num) this.currentMobile = num;
        this.callNumberService.makeCall(this.currentMobile,
            this.callNumberService.initClientNoteLog(this.currentCust.clientId),
            true,
            this.callNumberService.initFollowStateLog(this.currentCust.clientId));
    }

    /**
     * 拨打电话
     */
    callClickHandle(item) {
        this.currentCust = item;
        this.currentMobileList = item.mobilePhone;
        if (!this.currentMobileList || this.currentMobileList.length < 1) return;
        if (this.currentMobileList.length === 1 && this.currentMobileList[0].mobile) {
            this.currentMobile = this.currentMobileList[0].mobile;
            this.nativeCallPhone(this.currentMobile);
            return;
        }else{
            const phoneArray = [];
            this.currentMobileList.forEach(phoneNumItem => {
                phoneArray.push({
                    text:phoneNumItem.mobile,
                    handler:() => {
                        this.currentMobile = phoneNumItem.mobile;
                        this.nativeCallPhone();
                    }
                });
            });
            this.adpActionSheetController.create({
                title:"选择电话",
                buttons:phoneArray
            }).present();
        }
    }

    /**
     * 返回
     * @param ev
     */
    backButtonClick(ev) {
        ev.preventDefault();
        ev.stopPropagation();
        this.navCtrl && this.navCtrl.pop(null, null);
    }

    // 到客户详情
    goToClientDetail(item) {
        //const clientRole = role;
        /*if (role == 'O') {
            this.navCtrl.push('HolderClientDetailPage', {
                clientNum: id,
                role: clientRole
            })
        } else if (role == 'IO') {
            this.navCtrl.push('HolderClientDetailPage', {
                clientNum: id,
                role: clientRole
            })
        } else {
            this.navCtrl.push('InsuredClientDetailPage', {
                clientNum: id,
                role: clientRole
            })
        }*/
        this.navCtrl.push('HolderClientDetailPage', {
            clientNum: item.clientId,
            role:item.clientRole
        })
    }

    /**
     * 下拉刷新
     * @param refresher
     */
    doRefresh(refresher) {
        // this.getClientList(1, () => {
        //     refresher.complete();
        // });
        this.refreshing = true;
        this.pageParams.pageNum = 1;
        if (this.infiniteScroll) this.infiniteScroll.enable(true);
        this.getClientList(1, () => {
            this.refreshing = false;
            this.filterConditionsShow = true;
            refresher.complete()
        });
    }

    refreshing:boolean = false;
    filterConditionsShow = true;
    contentTouchEnd(){
        setTimeout(() => {
            if(!this.refreshing){
                this.filterConditionsShow = true;
            }
        },500);
    }

    selectChangeHandle(e) {
        this.pageParams.orderType = e.value;
        this.getClientList();
    }

    ionViewWillLeave() {
        this.clientFilterTool.destroy();
    }

}
